package blue.web.controller;

import blue.tools.constants.BlueContants;
import blue.erp.model.SysUser;
import blue.tools.commons.IpUtils;
import blue.tools.model.ResponseData;
import blue.web.commons.UserContext;
import blue.web.dao.service.SysRoleService;
import blue.web.dao.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configurable
@RestController
public class LoginController {
    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Value("${blue-erp.commons.loginUrl}")
    private String loginUrl;


    @RequestMapping("login")
    public ResponseData login(String username, String password, boolean rememberMe, HttpServletRequest request, HttpServletResponse response){

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, IpUtils.getIpAddr(request));
        rememberMe=true;
        if(rememberMe){
            token.setRememberMe(rememberMe);
        }
        Subject subject = SecurityUtils.getSubject();

        boolean result=false;

        try {
            subject.login(token);
            result=subject.isAuthenticated();
        } catch (Exception e) {

        }

        if(result){
            SysUser sysUser=UserContext.getContext();
            return new ResponseData(BlueContants.SUCCESS,"成功",sysUser);
        }

        try {
            if(StringUtils.isBlank(username)){//当密码过期或者黑客强行跳转的时候，直接跳转登陆页即可
                response.sendRedirect(loginUrl);
            }
        }catch (Exception e){

        }

        return new ResponseData(BlueContants.ERROR,"失败",null);
    }

    @RequestMapping("/checkLoginStatus")
    public void checkLoginStatus(String domain,HttpServletRequest request, HttpServletResponse response){

        SysUser user=UserContext.getContext();

        try {
            if(user==null || user.getId()==null){
                response.sendRedirect(loginUrl);
            }
        }catch (Exception e){

        }
    }

    @RequestMapping("accountLogout")
    public void logout(){
        SecurityUtils.getSubject().logout();
    }
}
